package 面试题;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: MENG
 * Date: 2022-07-12
 * Time: 19:22
 */
//用队列实现栈
public class MyStack {
    Queue<Integer> qu1;
    Queue<Integer> qu2;
    public int usedSize;

    public MyStack() {
        this.qu1 = new LinkedList<>();
        this.qu2 = new LinkedList<>();
    }

    public boolean empty() {
        return usedSize == 0;
    }
    public boolean empty2() {
        return qu1.isEmpty() && qu2.isEmpty();
    }

    //入栈，入到不为空的队列中去
    public void push(int x) {
        if(!qu1.isEmpty()){
            qu1.offer(x);
        }else if(!qu2.isEmpty()){
            qu2.offer(x);
        }else{
            qu1.offer(x);
        }
        usedSize++;

    }

    //出栈
    public int pop(){
        if(empty()) {
            return -1;
        }
        if(!qu1.isEmpty()){
            int curSize = qu1.size();
            for (int i = 0; i < curSize - 1; i++) {
                qu2.offer(qu1.poll());

            }
            usedSize--;
            return qu1.poll();
        }else{
            int curSize = qu2.size();
            for (int i = 0; i < curSize - 1; i++) {
                qu1.offer(qu2.poll());
            }
            usedSize--;
            return qu2.poll();
        }
    }
    //就是peek
    public int top(){
        if(empty()){
            return -1;
        }
        if(!qu1.isEmpty()){
            int curSize = qu1.size();
            int ret = -1;
            for (int i = 0; i < curSize; i++) {
                ret = qu1.poll();
                qu2.offer(ret);
            }
            return ret;
        }else{
            int curSize = qu2.size();
            int ret = -1;
            for (int i = 0; i < curSize; i++) {
                ret = qu2.poll();
                qu1.offer(ret);
            }
            return ret;
        }

    }

}